const express = require("express");
const router = express.Router();
const {
  addRecharge,
  getRecharge,
  calculateBalance,
  calculateTotalAmount,
  getRechargeAmount,
  addExpenditure,
  createRechargeRequest,
  getRechargeRequests,
  getUserRechargeRequests,
  processRechargeRequest,
} = require("../utils/sql");

// date, amount, method, user_id
router.post("/recharge", async (req, res) => {
  const { inform } = req.body;
  if (!inform || !Array.isArray(inform) || inform.length === 0) {
    return res.status(400).json({ message: "Invalid request body" });
  }

  const { date, amount, method, user_id } = inform[0];
  const result = await addRecharge(date, amount, method, user_id);
  if (result.affectedRows === 1) {
    return res.status(200).json({ message: "充值成功" });
  } else {
    return res.status(500).json({ message: "充值失败" });
  }
});

router.post("/getrecharge", async (req, res) => {
  const { user_id } = req.body;
  if (!user_id) {
    return res.status(400).json({ message: "查询参数错误" });
  }
  const result = await getRecharge(user_id);
  if (result.length > 0) {
    return res.status(200).json({ data: result });
  } else {
    return res.status(404).json({ message: "未查询到充值记录" });
  }
});
// 剩余金额
router.post("/calculateTotalAmount", async (req, res) => {
  const { user_id } = req.body;
  console.log(user_id);
  if (!user_id) {
    return res.status(400).json({ message: "查询参数错误" });
  }
  const result = await calculateTotalAmount(user_id);
  if (result !== null && result !== undefined) {
    return res.status(200).json({ data: result });
  } else {
    return res.status(404).json({ message: "未查询到充值记录" });
  }
});

// 使用的金额
router.post("/calculateBalance", async (req, res) => {
  const { user_id } = req.body;
  if (!user_id) {
    return res.status(400).json({ message: "查询参数错误" });
  }
  const result = await calculateBalance(user_id);
  if (result !== null && result !== undefined) {
    return res.status(200).json({ data: result });
  } else {
    return res.status(404).json({ message: "未查询到充值记录" });
  }
});

// 充值金额
router.post("/getRechargeAmount", async (req, res) => {
  const { user_id } = req.body;
  if (!user_id) {
    return res.status(400).json({ message: "查询参数错误" });
  }
  const result = await getRechargeAmount(user_id);
  if (result !== null && result !== undefined) {
    return res.status(200).json({ data: result });
  } else {
    return res.status(404).json({ message: "未查询到充值记录" });
  }
});

// 支出
router.post("/addExpenditure", async (req, res) => {
  const { date, amount, user_id } = req.body;
  const result = await addExpenditure(date, amount, user_id);
  if (result.affectedRows === 1) {
    return res.status(200).json({ message: "支出成功" });
  } else {
    return res.status(500).json({ message: "支出失败" });
  }
});

// 创建充值申请
router.post("/createRechargeRequest", async (req, res) => {
  try {
    const { user_id, amount, payment_method } = req.body;

    if (!user_id || !amount || !payment_method) {
      return res.status(400).json({
        code: 0,
        message: "参数不完整"
      });
    }

    if (amount <= 0) {
      return res.status(400).json({
        code: 0,
        message: "充值金额必须大于0"
      });
    }

    const result = await createRechargeRequest(user_id, amount, payment_method);

    if (result.affectedRows === 1) {
      return res.status(200).json({
        code: 200,
        message: "充值申请提交成功，请等待管理员审核",
        data: { request_id: result.insertId }
      });
    } else {
      return res.status(500).json({
        code: 0,
        message: "充值申请提交失败"
      });
    }
  } catch (err) {
    console.error("创建充值申请失败:", err);
    return res.status(500).json({
      code: 0,
      message: "服务器错误"
    });
  }
});

// 获取用户的充值申请记录
router.post("/getUserRechargeRequests", async (req, res) => {
  try {
    const { user_id } = req.body;

    if (!user_id) {
      return res.status(400).json({
        code: 0,
        message: "用户ID不能为空"
      });
    }

    const result = await getUserRechargeRequests(user_id);

    return res.status(200).json({
      code: 200,
      message: "获取成功",
      data: result
    });
  } catch (err) {
    console.error("获取用户充值申请失败:", err);
    return res.status(500).json({
      code: 0,
      message: "服务器错误"
    });
  }
});

// 获取所有充值申请（管理员用）
router.post("/getRechargeRequests", async (req, res) => {
  try {
    const { status } = req.body;

    const result = await getRechargeRequests(status);

    return res.status(200).json({
      code: 200,
      message: "获取成功",
      data: result
    });
  } catch (err) {
    console.error("获取充值申请失败:", err);
    return res.status(500).json({
      code: 0,
      message: "服务器错误"
    });
  }
});

// 处理充值申请（管理员审核）
router.post("/processRechargeRequest", async (req, res) => {
  try {
    const { request_id, admin_id, status, admin_comment } = req.body;

    if (!request_id || !admin_id || !status) {
      return res.status(400).json({
        code: 0,
        message: "参数不完整"
      });
    }

    if (!['approved', 'rejected'].includes(status)) {
      return res.status(400).json({
        code: 0,
        message: "无效的审核状态"
      });
    }

    // 更新申请状态
    const updateResult = await processRechargeRequest(request_id, admin_id, status, admin_comment);

    if (updateResult.affectedRows === 1) {
      // 如果审核通过，添加到充值记录
      if (status === 'approved') {
        // 获取申请详情
        const requests = await getRechargeRequests();
        const request = requests.find(r => r.id === parseInt(request_id));

        if (request) {
          // 添加到充值记录
          const rechargeResult = await addRecharge(
            new Date().toLocaleDateString(),
            request.amount,
            request.payment_method,
            request.user_id
          );

          if (rechargeResult.affectedRows === 1) {
            return res.status(200).json({
              code: 200,
              message: "审核成功，充值已到账"
            });
          } else {
            return res.status(500).json({
              code: 0,
              message: "审核成功但充值记录添加失败"
            });
          }
        }
      } else {
        return res.status(200).json({
          code: 200,
          message: "申请已拒绝"
        });
      }
    } else {
      return res.status(500).json({
        code: 0,
        message: "审核失败"
      });
    }
  } catch (err) {
    console.error("处理充值申请失败:", err);
    return res.status(500).json({
      code: 0,
      message: "服务器错误"
    });
  }
});

module.exports = router;
